<?php
/**
 * 获取用户信息类
 * Created by PhpStorm.
 * User: Sunwu
 * Date: 2017/9/21
 * Time: 10:51
 */

class WeChatUserInfo{
    private $_appid;//appid
    private $_secret;//secret

    public function __construct($appid,$secret)
    {
        $this->_appid=$appid;
        $this->_secret=$secret;
    }


    /**
     * 获取access_token和openid
     * @return array
     */
    public function getWebAccessTokenAndOpenId(){
        $code=$_GET['code'];//用户点授权后获得的code
        $webAccessTokenAPI="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->_appid&secret=$this->_secret&code=$code&grant_type=authorization_code";
        $webAccessTokenAPIRes=Curl::doGet($webAccessTokenAPI);
        $webAccessTokenAPIRes=json_decode($webAccessTokenAPIRes,true);
        $accessToken=$webAccessTokenAPIRes['access_token'];
        $openId=$webAccessTokenAPIRes['openid'];
        return array($accessToken,$openId);
    }

    /**
     * 获取用户信息
     * @return array
     */
    public function getUserInfo()
    {
        $res=$this->getWebAccessTokenAndOpenId();
        $accessToken=$res[0];
        $openId=$res[1];
        $userInfoAPI="https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openId&lang=zh_CN";
        $userInfoAPIRes=Curl::doGet($userInfoAPI);
        $userInfo=json_decode($userInfoAPIRes,true);
        return $userInfo;
    }
}